<template>
  <div class="login-register-container">
    <div class="card-container" :class="{ 'show-register': showRegister }">
      <!-- 左侧表单区 -->
      <div class="form-side">
        <el-form v-if="!showRegister" ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
          <h3 class="title">{{ title }} - 登录</h3>
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
              <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="loginForm.password" type="password" auto-complete="off" placeholder="密码" @keyup.enter.native="handleLogin">
              <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
            </el-input>
          </el-form-item>
          <el-form-item prop="code" v-if="captchaEnabled">
            <el-input v-model="loginForm.code" auto-complete="off" placeholder="验证码" style="width: 63%" @keyup.enter.native="handleLogin">
              <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
            </el-input>
            <div class="login-code">
              <img :src="loginCodeUrl" @click="getLoginCode" class="login-code-img"/>
            </div>
          </el-form-item>
          <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
          <el-form-item style="width:100%;">
            <el-button :loading="loginLoading" size="medium" type="primary" style="width:100%;" @click.native.prevent="handleLogin">
              <span v-if="!loginLoading">登录</span>
              <span v-else>登录中...</span>
            </el-button>
          </el-form-item>
        </el-form>
        <el-form v-else ref="registerForm" :model="registerForm" :rules="registerRules" class="register-form">
          <h3 class="title">{{ title }} - 注册</h3>
          <el-form-item prop="username">
            <el-input v-model="registerForm.username" type="text" auto-complete="off" placeholder="账号">
              <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="registerForm.password" type="password" auto-complete="off" placeholder="密码" @keyup.enter.native="handleRegister">
              <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
            </el-input>
          </el-form-item>
          <el-form-item prop="confirmPassword">
            <el-input v-model="registerForm.confirmPassword" type="password" auto-complete="off" placeholder="确认密码" @keyup.enter.native="handleRegister">
              <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
            </el-input>
          </el-form-item>
          <el-form-item prop="code" v-if="captchaEnabled">
            <el-input v-model="registerForm.code" auto-complete="off" placeholder="验证码" style="width: 63%" @keyup.enter.native="handleRegister">
              <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
            </el-input>
            <div class="register-code">
              <img :src="registerCodeUrl" @click="getRegisterCode" class="register-code-img"/>
            </div>
          </el-form-item>
          <el-form-item style="width:100%;">
            <el-button :loading="registerLoading" size="medium" type="primary" style="width:100%;" @click.native.prevent="handleRegister">
              <span v-if="!registerLoading">注册</span>
              <span v-else>注册中...</span>
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 右侧切换区 -->
      <div class="switch-side">
        <div v-if="!showRegister" class="switch-panel">
          <h2>还没有账号？</h2>
          <p>点击注册，加入我们！</p>
          <el-button type="primary" @click="handleSwitchRegister" class="switch-btn">注册</el-button>
        </div>
        <div v-else class="switch-panel">
          <h2>已有账号？</h2>
          <p>点击登录，返回登录页</p>
          <el-button type="primary" @click="handleSwitchLogin" class="switch-btn">登录</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getCodeImg, register } from "@/api/login"
import Cookies from "js-cookie"
import { encrypt, decrypt } from '@/utils/jsencrypt'

export default {
  name: "LoginRegister",
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.registerForm.password !== value) {
        callback(new Error("两次输入的密码不一致"))
      } else {
        callback()
      }
    }
    return {
      title: process.env.VUE_APP_TITLE,
      // 登录相关
      loginForm: {
        username: "admin",
        password: "admin123",
        rememberMe: false,
        code: "",
        uuid: ""
      },
      loginRules: {
        username: [
          { required: true, trigger: "manual", message: "请输入您的账号" }
        ],
        password: [
          { required: true, trigger: "manual", message: "请输入您的密码" }
        ],
        code: [{ required: true, trigger: "manual", message: "请输入验证码" }]
      },
      loginLoading: false,
      loginCodeUrl: "",
      // 注册相关
      registerForm: {
        username: "",
        password: "",
        confirmPassword: "",
        code: "",
        uuid: ""
      },
      registerRules: {
        username: [
          { required: true, trigger: "manual", message: "请输入您的账号" },
          { min: 2, max: 20, message: '用户账号长度必须介于 2 和 20 之间', trigger: 'manual' }
        ],
        password: [
          { required: true, trigger: "manual", message: "请输入您的密码" },
          { min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "manual" },
          { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\ |", trigger: "manual" }
        ],
        confirmPassword: [
          { required: true, trigger: "manual", message: "请再次输入您的密码" },
          { required: true, validator: equalToPassword, trigger: "manual" }
        ],
        code: [{ required: true, trigger: "manual", message: "请输入验证码" }]
      },
      registerLoading: false,
      registerCodeUrl: "",
      // 公共
      captchaEnabled: true,
      showRegister: false
    }
  },
  created() {
    this.getLoginCode()
    this.getRegisterCode()
    this.getCookie()
  },
  methods: {
    // 登录相关
    getLoginCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
        if (this.captchaEnabled) {
          this.loginCodeUrl = "data:image/gif;base64," + res.img
          this.loginForm.uuid = res.uuid
        }
      })
    },
    getCookie() {
      const username = Cookies.get("username")
      const password = Cookies.get("password")
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      }
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loginLoading = true
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 })
            Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 })
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 })
          } else {
            Cookies.remove("username")
            Cookies.remove("password")
            Cookies.remove('rememberMe')
          }
          this.$store.dispatch("Login", this.loginForm).then(() => {
            this.$router.push({ path: "/" }).catch(()=>{})
          }).catch(() => {
            this.loginLoading = false
            if (this.captchaEnabled) {
              this.getLoginCode()
            }
          })
        }
      })
    },
    // 注册相关
    getRegisterCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
        if (this.captchaEnabled) {
          this.registerCodeUrl = "data:image/gif;base64," + res.img
          this.registerForm.uuid = res.uuid
        }
      })
    },
    handleRegister() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          this.registerLoading = true
          register(this.registerForm).then(res => {
            const username = this.registerForm.username
            this.$alert(`<font color='red'>恭喜你，您的账号 ${username} 注册成功！</font>`, '系统提示', {
              dangerouslyUseHTMLString: true,
              type: 'success'
            }).then(() => {
              this.showRegister = false
            }).catch(() => {})
          }).catch(() => {
            this.registerLoading = false
            if (this.captchaEnabled) {
              this.getRegisterCode()
            }
          })
        }
      })
    },
    handleSwitchRegister() {
      this.showRegister = true;
      this.$nextTick(() => {
        this.$refs.registerForm && this.$refs.registerForm.resetFields();
      });
    },
    handleSwitchLogin() {
      this.showRegister = false;
      this.$nextTick(() => {
        this.$refs.loginForm && this.$refs.loginForm.resetFields();
      });
    }
  }
}
</script>

<style scoped lang="scss">
.login-register-container {
  width: 100vw;
  height: 100vh;
  background: url('https://images.unsplash.com/photo-1506744038136-46273834b3fb?auto=format&fit=crop&w=1500&q=80') center center/cover no-repeat;
  display: flex;
  align-items: center;
  justify-content: center;
}

.card-container {
  width: 800px;
  height: 500px;
  display: flex;
  border-radius: 24px;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.18);
  overflow: hidden;
  background: rgba(255,255,255,0.15);
  backdrop-filter: blur(10px);
  transition: all 0.5s cubic-bezier(.4,2.08,.55,.44);
}

.form-side, .switch-side {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255,255,255,0.7);
  transition: all 0.5s;
}

.form-side {
  padding: 40px 32px;
  min-width: 340px;
}

.switch-side {
  flex-direction: column;
  text-align: center;
  background: rgba(255,255,255,0.25);
  justify-content: center;
}

.switch-panel h2 {
  color: #333;
  font-size: 26px;
  margin-bottom: 10px;
}
.switch-panel p {
  color: #666;
  margin-bottom: 30px;
}
.switch-btn {
  border-radius: 22px;
  width: 120px;
  font-size: 16px;
  font-weight: bold;
  background: linear-gradient(90deg, #0093E9 0%, #80D0C7 100%);
  border: none;
  color: #fff;
}

.title {
  color: #17c0ae;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 30px;
  text-align: center;
  letter-spacing: 2px;
}

.el-input__inner, .el-input input {
  background: #fff !important;
  border: 1px solid #e0e0e0 !important;
  border-radius: 4px !important;
  color: #333 !important;
  font-size: 16px;
  box-shadow: none;
}

.el-form-item {
  margin-bottom: 22px !important;
}

.el-button {
  border-radius: 22px !important;
  font-size: 16px;
  font-weight: bold;
  letter-spacing: 2px;
  width: 100%;
  height: 44px;
  background: linear-gradient(90deg, #0093E9 0%, #80D0C7 100%);
  color: #fff;
  border: none;
}

.login-code, .register-code {
  display: inline-block;
  vertical-align: middle;
  margin-left: 10px;
  .login-code-img, .register-code-img {
    height: 38px;
    border-radius: 6px;
    cursor: pointer;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  }
}

@media (max-width: 900px) {
  .card-container {
    flex-direction: column;
    width: 98vw;
    height: auto;
    min-width: 0;
    min-height: 0;
  }
  .form-side, .switch-side {
    min-width: 0;
    width: 100%;
    padding: 30px 10px;
  }
}
</style>

